package fatworm.storage.types;

import fatworm.query.constant.*;
import fatworm.storage.table.*;
import fatworm.util.*;

public class SInt extends SType
{
    private Integer val;

    public SInt()
    {
        val = null;
    }
    public SInt(Integer val)
    {
        this.val = val;
    }
    @Override
    public void fromBytes(byte[] bytes)
    {
        if (bytes.length != 5)
            throw new Error("!!!");
        Lib.assertTrue(bytes[0] == NULLFLAG || bytes[0] == NOTNULLFLAG);
        if (bytes[0] == NULLFLAG)
            val = null;
        else
            val = Lib.bytesToInt(bytes, 1);
    }
    @Override
    public byte[] toBytes()
    {
        byte[] res = new byte[5];
        if (val == null)
        {
            res[0] = NULLFLAG;
        } else
        {
            res[0] = NOTNULLFLAG;
            Lib.bytesFromInt(res, 1, val);
        }
        return res;
    }
    @Override
    public byte[] toBytesAsVID(VID vid)
    {
        throw new Error("!!!");
    }
    @Override
    public int length()
    {
        return 5;
    }
    @Override
    public int lengthAsVID()
    {
        throw new Error("!!!");
    }
    @Override
    public int getType()
    {
        return Types.INT;
    }
    @Override
    public Constant toConstant()
    {
        if (val == null)
            return new NullConstant();
        else
            return new IntConstant(val);
    }
    @Override
    public void fromConstant(Constant c)
    {
        if (c instanceof NullConstant)
        {
            val = null;
        } else if (c instanceof IntConstant)
        {
            val = (Integer) c.asJavaVal();
        } else
            throw new Error("!!!");
    }
    @Override
    public SType newInstance()
    {
        return new SInt();
    }
    @Override
    public SInt copy()
    {
        return new SInt(this.val);
    }
}
